package dao

import (
	"errors"
	"gitee.com/gopher2011/bookman/util"
)

// 这是 Member 的全局公开dao对象
var MemberDao = memberDao{}

// 注意:这是 Member 的私有dao对象
type memberDao struct {
	Obj    Member
	Insert func(arg Member) int64  //插入一条记录
	Update func(arg Member) int64  //更新一条记录
	Delete func(arg Member) int64  //删除一条记录
	Select func(arg Member) Member //获取一条记录
	Exist  func(arg Member) Member
	Login  func(account, email, password string) Member `arg:"account,email,password"`
	Find   func(id int) Member                          `arg:"id"`
	GetAll func(uid int) Member                         `arg:"member_id"`
}

// 注册一个用户
func (it *memberDao) Register(arg Member) error {
	obj := it.Exist(arg)
	if obj.Nickname == arg.Nickname {
		return errors.New("昵称已存在，请更换昵称")
	}
	if obj.Email == arg.Email {
		return errors.New("邮箱已被注册，请更换邮箱")
	}
	if obj.Account == arg.Account {
		return errors.New("用户名已存在，请更换用户名")
	}

	if arg.Account == "admin" {
		arg.Role = MemberSuperRole
	} else {
		arg.Role = MemberGeneralRole
	}
	arg.Password = util.MD5V([]byte(arg.Password))
	if arg.AuthMethod == "" {
		arg.AuthMethod = "local"
	}
	switch arg.Role {
	case MemberSuperRole:
		it.Obj.RoleName = "超级管理员"
	case MemberAdminRole:
		it.Obj.RoleName = "管理员"
	case MemberGeneralRole:
		it.Obj.RoleName = "读者"
	case MemberEditorRole:
		it.Obj.RoleName = "作者"
	}
	if id := it.Insert(arg); id <= 0 {
		return errors.New("新增一个用户失败")
	}
	return nil
}
